package edu.hubu.web.config;

import edu.hubu.web.commons.ResultsJson;
import edu.hubu.web.exception.*;
import org.springframework.context.annotation.Configuration;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * @author moonlan
 * date 2020/11/18 17:42
 */
@SuppressWarnings(value = "unused")
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
    @Override
    public void configureHandlerExceptionResolvers(List<HandlerExceptionResolver> resolvers) {
        resolvers.add((httpServletRequest, httpServletResponse, o, e) -> {
            httpServletResponse.setStatus(HttpServletResponse.SC_OK);
            httpServletResponse.setContentType("application/json;charset=utf-8");
            if (e instanceof SyntaxErrorException || e instanceof IllegalArgumentException) {
                ResultsJson.toJson(400, e.getMessage(), 1, 0, null, httpServletResponse);
            } else if (e instanceof AccessDeniedException) {
                ResultsJson.toJson(403, e.getMessage(), 1, 0, null, httpServletResponse);
            } else if (e instanceof InformationNotFoundException) {
                ResultsJson.toJson(404, e.getMessage(), 1, 0, null, httpServletResponse);
            } else if (e instanceof HttpRequestMethodNotSupportedException) {
                ResultsJson.toJson(405, e.getMessage(), 1, 0, null, httpServletResponse);
            } else if (e instanceof WrongUsernameOrPasswordException) {
                ResultsJson.toJson(411, e.getMessage(), 1, 0, null, httpServletResponse);
            } else if (e instanceof InternalServerException) {
                ResultsJson.toJson(500, e.getMessage(), 1, 0, null, httpServletResponse);
            } else if (e instanceof ClientException) {
                ResultsJson.toJson(413, e.getMessage(), 1, 0, null, httpServletResponse);
            } else if (e instanceof UsernameNotFoundException) {
                ResultsJson.toJson(410, e.getMessage(), 1, 0, null, httpServletResponse);
            } else if (e instanceof DataIntegrityViolationException) {
                ResultsJson.toJson(414, "数据不合法", 1, 0, null, httpServletResponse);
            } else {
                System.out.println(e);
                ResultsJson.toJson(512, "未知错误，请联系管理员", 1, 0, null, httpServletResponse);
            }

            return new ModelAndView();
        });
    }
}
